﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using PropertyExpression.Common;

namespace PropertyExpression.ControllableQuery.Demo
{
    class Program
    {
        static void Main()
        {
            foreach (var post in GetValue(DateTime.Now))
                Console.WriteLine(post.CreationDate);
        }

        private static List<IPost> GetValue(DateTime? date)
        {
            using (var connection = new SqlConnection(DALTest.ConnectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    var qFragment = new {date}.QFragment(@"
SELECT  TOP 10
        Id, CreationDate
FROM    Post
WHERE   1 = 1
@if (date.HasValue) {
        @:AND CreationDate <= @date
}");
                    return command.Fill(qFragment).ExecuteEnumerable<IPost>().ToList();
                }
            }
        }

        static Program()
        {
            RegisterRazorConfiguration();
        }

        private static void RegisterRazorConfiguration([CallerFilePath] string filePath = "")
        {
            RazorConfiguration.Register(filePath, new string[] {}, MethodBase.GetCurrentMethod());
        }
    }

    public static class SqlCommandExtensions
    {
        public static IEnumerable<T> ExecuteEnumerable<T>(this SqlCommand it)
        {
            using (var reader = it.ExecuteReader())
                while (reader.Read())
                    yield return reader.Materialize<T>();
        }        
    }
}
